<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ collapsed: isCollapsed }">
      <!-- 用户资料 -->
      <div class="user-profile">
        <div class="avatar" @click="showAvatarDialog">
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar-img" />
          <span v-else class="iconfont-user">员</span>
        </div>
        <div class="user-info" v-if="!isCollapsed">
          <div class="name">员工</div>
          <div class="position">员工操作台</div>
        </div>
      </div>

      <!-- 主菜单 -->
      <nav class="menu">
        <div v-for="item in menuItems" :key="item.id" class="menu-item" :class="{ active: isMenuActive(item.link) }"
          @click="navigateTo(item.link)">
          <span class="iconfont" :class="item.icon"></span>
          <span class="text" v-if="!isCollapsed">{{ item.name }}</span>
        </div>
      </nav>

      <!-- 底部菜单 -->
      <div class="footer-menu">
        <div class="menu-item" @click="handleSettings">
          <span class="iconfont icon-setting"></span>
          <span class="text" v-if="!isCollapsed">设置</span>
        </div>
        <div class="menu-item" @click="handleLogout">
          <span class="iconfont icon-logout"></span>
          <span class="text" v-if="!isCollapsed">退出登录</span>
        </div>
        <div class="expiry" v-if="!isCollapsed">
          剩余 {{ daysToExpire }} 天到期
        </div>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部导航栏 -->
      <header class="top-header">
        <div class="header-left">
          <button class="toggle-btn" @click="toggleSidebar">
            <span class="iconfont" :class="isCollapsed ? 'icon-ar-right' : 'icon-ar-left'"></span>
          </button>
          <div class="breadcrumb">
            工作台 <small>/</small>
            {{ activeMenuName }}
          </div>
        </div>
        <div class="header-right">
          <span class="header-item" @click="navigateToContact">
            <i class="iconfont icon-help"></i>联系我们
          </span>
        </div>
      </header>

      <!-- 页面内容 -->
      <div class="content">
        <router-view></router-view>
      </div>
    </main>

    <!-- 头像修改对话框 -->
    <div class="avatar-dialog" v-if="avatarDialogVisible">
      <div class="dialog-mask" @click="hideAvatarDialog"></div>
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>修改头像</h3>
          <button class="close-btn" @click="hideAvatarDialog">
            <span class="iconfont icon-close"></span>
          </button>
        </div>
        <div class="dialog-body">
          <div class="avatar-preview">
            <img v-if="previewAvatar" :src="previewAvatar" class="preview-img" />
            <div v-else class="avatar-placeholder">
              <span class="iconfont icon-user"></span>
            </div>
          </div>
          <div class="upload-controls">
            <input type="file" id="avatar-upload" ref="fileInput" accept="image/*" @change="handleFileChange"
              style="display: none" />
            <button class="upload-btn" @click="triggerFileInput">
              <span class="iconfont icon-upload"></span>
              选择图片
            </button>
            <button class="confirm-btn" :disabled="!selectedFile" @click="uploadAvatar">
              确认上传
            </button>
          </div>
          <div class="crop-controls" v-if="selectedFile">
            <div class="zoom-control">
              <span class="iconfont icon-zoom-out" @click="zoomOut"></span>
              <input type="range" min="1" max="3" step="0.1" v-model="zoomLevel" @input="updateZoom" />
              <span class="iconfont icon-zoom-in" @click="zoomIn"></span>
            </div>
            <button class="rotate-btn" @click="rotateImage">
              <span class="iconfont icon-rotate"></span>
              旋转
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { vToast } from '@/plugins/vToast'
import { vConfirm } from '@/plugins/vConfirm'
import { get } from '@/request'
import { useUserInfoStore } from '@/store/userInfoStore'

const router = useRouter();
const route = useRoute();

// 状态管理
const isCollapsed = ref(false);
const daysToExpire = ref(30);

// 头像相关状态
const avatarUrl = ref(localStorage.getItem('avatarUrl') || '');
const avatarDialogVisible = ref(false);
const selectedFile = ref(null);
const previewAvatar = ref('');
const zoomLevel = ref(1);
const rotation = ref(0);
const fileInput = ref(null);

// 获取用户首字母
const userInitial = computed(() => {
  return '管理员'.charAt(0);
});

// 显示头像对话框
const showAvatarDialog = () => {
  avatarDialogVisible.value = true;
  // 重置状态
  selectedFile.value = null;
  previewAvatar.value = '';
  zoomLevel.value = 1;
  rotation.value = 0;
};

// 隐藏头像对话框
const hideAvatarDialog = () => {
  avatarDialogVisible.value = false;
};

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 检查文件类型
  if (!file.type.match('image.*')) {
    alert('请选择图片文件');
    return;
  }

  // 检查文件大小 (限制5MB)
  if (file.size > 5 * 1024 * 1024) {
    alert('图片大小不能超过5MB');
    return;
  }

  selectedFile.value = file;

  // 创建预览
  const reader = new FileReader();
  reader.onload = (e) => {
    previewAvatar.value = e.target.result;
  };
  reader.readAsDataURL(file);
};

// 上传头像
const uploadAvatar = () => {
  if (!selectedFile.value) return;

  // 这里应该是实际的上传逻辑
  // 模拟上传过程
  console.log('上传头像:', selectedFile.value);

  // 模拟上传成功
  setTimeout(() => {
    avatarUrl.value = previewAvatar.value;
    localStorage.setItem('avatarUrl', avatarUrl.value);
    hideAvatarDialog();
    alert('头像更新成功');
  }, 1000);
};

// 缩放控制
const zoomIn = () => {
  if (zoomLevel.value < 3) {
    zoomLevel.value += 0.1;
  }
};

const zoomOut = () => {
  if (zoomLevel.value > 1) {
    zoomLevel.value -= 0.1;
  }
};

const updateZoom = () => {
  // 这里可以更新预览图的缩放
  console.log('缩放级别:', zoomLevel.value);
};

// 旋转图片
const rotateImage = () => {
  rotation.value = (rotation.value + 90) % 360;
  console.log('旋转角度:', rotation.value);
};

// 组件挂载时初始化
onMounted(() => {
  // 初始化逻辑
});

// 菜单数据
const menuItems = [
  {
    id: "dashboard",
    name: "工作台",
    icon: "icon-dashboard",
    link: "/workspace",
  },
  // {
  //   id: "person",
  //   name: "人员管理",
  //   icon: "icon-money",
  //   link: "/workspace/dict",
  // },
  // {
  //   id: "person",
  //   name: "员工任务明细",
  //   icon: "icon-money",
  //   link: "/workspace/user/task",
  // },
  // {
  //   id: "rili",
  //   name: "日历任务",
  //   icon: "icon-money",
  //   link: "/workspace/user/calendar",
  // },
  {
    id: "finance",
    name: "财务管理",
    icon: "icon-money",
    link: "/workspace/finance",
  },
  {
    id: "orders",
    name: "订单状态",
    icon: "icon-order",
    link: "/workspace/orders",
  },
  {
    id: "messages",
    name: "消息中心",
    icon: "icon-message",
    link: "/workspace/messages",
  },
];

// 自定义激活状态判断
const isMenuActive = (link) => {
  // 对于工作台特殊处理，只有当路径完全匹配时才激活
  if (link === '/workspace') {
    return route.path === link;
  }
  return route.path.startsWith(link);
};

const navigateTo = (link) => {
  router.push(link);
};

// 导航到联系我们
const navigateToContact = () => {
  console.log("跳转到联系我们页面");
};

// 计算当前菜单名称
const activeMenuName = computed(() => {
  const matchedRoute = route.matched[0]?.path || '';
  const menu = menuItems.find(item => {
    if (item.link === '/workspace') {
      return route.path === item.link;
    }
    return matchedRoute.includes(item.link);
  });
  return menu?.name || "工作台";
});

// 切换侧边栏
const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 处理设置
const handleSettings = () => {
  console.log("打开设置");
};

// 处理退出登录
const handleLogout = () => {
  vConfirm({
    message: '确定要退出登录吗？',
    confirmText: '确定',
    cancelText: '取消'
  }).then(() => {
    // 清除用户信息和token
    localStorage.removeItem('userInfo');
    localStorage.removeItem('avatarUrl');
    localStorage.removeItem('token');
    // 跳转到登录页
    router.push('/user/login');
  }).catch(() => {
    // 取消退出登录，不做任何处理
  });
}
</script>

<style scoped lang="less">
.admin-layout {
  display: flex;
  height: 100vh;
  color: #323335;
}

/* 侧边栏样式 */
.sidebar {
  width: 240px;
  background-color: #f1f2f6;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
}

.sidebar.collapsed {
  width: 80px;
}

/* 用户资料区域 */
.user-profile {
  padding: 40px 20px;
  display: flex;
  align-items: center;
}

.avatar {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background-color: #3f91f7;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  cursor: pointer;
  overflow: hidden;
  position: relative;
  transition: all 0.3s;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  }

  .avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .iconfont-user {
    font-size: 24px;
  }
}

.user-info {
  margin-left: 12px;
}

.name {
  font-weight: 600;
  font-size: 20px;
}

.position {
  font-size: 16px;
  color: #7a7d81;
}

/* 菜单区域 */
.menu {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 6px;
  text-decoration: none;
  color: inherit;
}

.menu-item:hover {
  color: #3f91f7;
}

.menu-item.active {
  background-color: #fff;
  color: #3f91f7;
}

.menu-item .icon {
  font-size: 20px;
  width: 24px;
  text-align: center;
}

.menu-item .text {
  margin-left: 12px;
  white-space: nowrap;
}

/* 底部菜单 */
.footer-menu {
  border-top: 1px solid #e4e5e9;
  padding: 10px 0;
}

.expiry {
  margin: 10px 20px;
  padding: 6px;
  border-radius: 4px;
  font-size: 12px;
  color: #ed8634;
  text-align: center;
  background: rgba(0, 0, 0, .1);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  min-width: 0;
  /* 防止内容溢出 */
  overflow-y: auto;
}

/* 顶部导航栏 */
.top-header {
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
}

.toggle-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  margin-right: 20px;
  color: #323335;
  width: 32px;
  height: 32px;
  padding: 0;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: #ddd 1px solid;
}

.toggle-btn:hover {
  background-color: #f1f2f6;
}

.breadcrumb {
  font-size: 14px;
  font-weight: 500;

  small {
    padding: 0 14px;
    color: #aaa;
  }
}

.header-right {
  display: flex;
}

.header-item {
  margin-left: 20px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;

  .iconfont {
    font-size: 18px;
  }
}

.header-item:hover {
  color: #3f91f7;
}

/* 内容区域 */
.content {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.content h2 {
  margin-bottom: 16px;
  font-weight: 600;
}

.content-inner {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 头像修改对话框样式 */
.avatar-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.dialog-content {
  position: relative;
  width: 500px;
  max-width: 90%;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  z-index: 1001;
  overflow: hidden;
}

.dialog-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  color: #999;
  padding: 4px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background-color: #f5f5f5;
    color: #666;
  }
}

.dialog-body {
  padding: 20px;
}

.avatar-preview {
  width: 200px;
  height: 200px;
  margin: 0 auto 20px;
  border-radius: 50%;
  background-color: #f5f5f5;
  overflow: hidden;
  position: relative;
  border: 2px dashed #ddd;

  .preview-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;

    .iconfont {
      font-size: 48px;
    }
  }
}

.upload-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 20px;
}

.upload-btn,
.confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  border: none;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
}

.upload-btn {
  background-color: #3f91f7;
  color: white;

  &:hover {
    background-color: #2a7de1;
  }
}

.confirm-btn {
  background-color: #67c23a;
  color: white;

  &:hover:not(:disabled) {
    background-color: #5daf34;
  }

  &:disabled {
    background-color: #c0c4cc;
    cursor: not-allowed;
    opacity: 0.7;
  }
}

.crop-controls {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.zoom-control {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;

  input[type="range"] {
    flex: 1;
  }

  .iconfont {
    cursor: pointer;
    font-size: 18px;
    color: #666;
    padding: 4px;

    &:hover {
      color: #3f91f7;
    }
  }
}

.rotate-btn {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 0 auto;
  transition: all 0.2s;

  &:hover {
    background-color: #e0e0e0;
  }

  .iconfont {
    font-size: 16px;
  }
}

/* 图标字体样式 */
.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-close:before {
  content: "✕";
}

.icon-upload:before {
  content: "↑";
}

.icon-zoom-in:before {
  content: "+";
}

.icon-zoom-out:before {
  content: "-";
}

.icon-rotate:before {
  content: "↻";
}

.icon-user:before {
  content: "👤";
}
</style>